import { Injectable } from '@nestjs/common';
import { UserDto, UserUpdateDto } from './dto/user.dto';
import { JwtService } from '@nestjs/jwt';
import { MongodbService } from '../../database/mongodb/mongodb.service';
import { BusinessException } from '../../types/exception/business.exception';
import { ERR_MSG } from '../../types/errcode';
import * as _ from 'lodash';
import { LoginDto } from './dto/login.dto';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class UserService {
  constructor(
    private readonly _mongodbService: MongodbService,
    private readonly _jwtService: JwtService,
  ) {}

  // 用户登录
  async login(body: LoginDto) {
    console.log('登录的参数', body);

    // 1.先判断当前用户是否存在
    const userInfo = await this._mongodbService.UserModel.findOne({
      userName: body.userName,
    });
    if (_.isEmpty(userInfo)) throw new BusinessException(ERR_MSG.LOGIN_NOT_EXIST, '');

    // 2. 判断密码是否正确
    if (userInfo.passWord !== body.passWord) {
      throw new BusinessException(ERR_MSG.LOGIN_NOT_CORRECT, '');
    }

    // 3.获取该用户对应的权限，将其包在token中返回 --TODO

    const returnData = {
      userName: userInfo.userName,
      id: userInfo.id,
    };

    const token = this._jwtService.sign(returnData);

    return { token };
  }

  // 获取用户列表
  async getUserList(req) {
    const { skip, limit } = req.herin;

    const list = await this._mongodbService.UserModel.aggregate([{ $skip: skip ? skip : 0 }, { $limit: limit ? limit : 10 }, { $project: { _id: 0, __v: 0 } }]);

    const total = await this._mongodbService.UserModel.countDocuments();

    return { list, total };
  }

  // 新增用户
  async addUser(req, UserDto: UserDto) {
    // 1. 校验当前用户是否存在
    const checkExist = await this._mongodbService.UserModel.findOne({
      userName: UserDto.userName,
    });
    if (!_.isEmpty(checkExist)) {
      throw new BusinessException(ERR_MSG.CHECK, '该账号已存在');
    }

    // 存储
    const returnData = await this._mongodbService.UserModel.create({
      // id
      id: uuidv4().replace(/-/g, ''),

      // 用户账号
      userName: UserDto.userName,

      // 用户密码
      passWord: UserDto.passWord ?? 'herin123',

      realName: UserDto.realName,

      departID: UserDto.depatID,
    });

    return { msg: returnData.userName + '-用户创建成功' };
  }

  // 更新用户
  async updateUser(req, UserUpdateDto: UserUpdateDto) {
    const { id, ...updateData } = UserUpdateDto;

    const user = await this._mongodbService.UserModel.findOne({
      id: id,
    });
    if (_.isEmpty(user)) {
      throw new BusinessException(ERR_MSG.LOGIN_NOT_EXIST);
    }

    const res = await this._mongodbService.UserModel.updateOne({ id: id }, { $set: updateData });
    if (res.modifiedCount > 0) {
      return { msg: '更新成功' };
    } else {
      return { msg: '更新成功' };
    }
  }

  // 删除用户
  async deleteUser(req, body: any) {
    const { ids } = body;

    if (ids.length <= 0) {
      throw new BusinessException({
        msg: '请提供要删除的项',
        code: '10001',
      });
    }
    const delInfo = await this._mongodbService.UserModel.deleteMany({
      id: { $in: ids },
    });

    return { msg: true, delInfo };
  }
}
